<template>
	<view class="container">
		<view>
			<view v-if='stores && stores.length == 0' style='padding:20vh 15%;font-size:12px;'>
				<view v-if='noGps'>
					<u-empty text="定位失败,请检查" mode="address"></u-empty>
					<view>1.手机系统设置中<text class='tips'>"微信"的定位权</text>限是否开启。</view>
					<view style='padding-top:10px'>2.<text class='tips'>手机GPS</text>是否打开。</view>
				</view>
				<view v-else>
					<u-empty text="搜索不到满足条件的门店" mode="search"></u-empty>
				</view>
			</view>
			<view v-else>
				<view v-for="item in stores" class='list'>
					<view style="padding-top:10px" @click="chooseStore(item)">
						<u-row>
							<u-col span="10" @click="chooseStore(item)">
								<view class="name" @click="chooseStore(item)">{{item.name}}</view>
								<view class="sub-title" style='padding-left:10px;'>{{item.address}}</view>
							</u-col>
							<u-col span="2">
								<view class="more">
									<u-icon name="arrow-right" size="22">
									</u-icon>
								</view>
							</u-col>
						</u-row>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				stores: [],
				myLat: '',
				myLon: '',
				storeId: 0,
				refundUrl: '',
				noGps: false,
				weekday: '',
				regions: [],
				showRegions: false,
				city: '江门',
				regionId: 6,
				keyword: '',
				isSupperUser: true
			}
		},
		onShow() {
			this.storeId = uni.getStorageSync('store')
			this.getStores()
			// let date = new Date()
			// let weekday = date.getDay()
			// console.log('week', weekday)
			// this.weekday = weekday
		},
		onLoad(options) {
			// if (typeof(options.refundUrl) != 'undefined') {
			// 	this.refundUrl = options.refundUrl
			// }
			// this.request.get(`api/regions`).then((res) => {
			// 	console.log('regins',res.data)
			// 	this.regions = res.data
			// })
		},
		methods: {
			getStores(){
				this.request.get(`public/stores`,{
					'@filter': `entity.getStatus() == 0`
				}).then((res) => {
					this.stores = res.data
				})
			},
			chooseStore(item) {
				uni.removeStorageSync('cart')
				uni.setStorageSync('store', item)
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			toMap(store) {
				console.log(store)
				uni.openLocation({
					latitude: store.latitude,
					longitude: store.longitude,
					scale: 18,
					name: store.name,
					address: store.address
				})
			},
			getDistance(storeLat, storeLon) {
				var radLat1 = this.myLat * Math.PI / 180.0;
				var radLat2 = storeLat * Math.PI / 180.0;
				var a = radLat1 - radLat2;
				var b = this.myLon * Math.PI / 180.0 - storeLon * Math.PI / 180.0;
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137; // EARTH_RADIUS;
				s = Math.round(s * 10000) / 10000;
				return s.toFixed(2);
			},
			getLocationInfo() { //2. 获取地理位置
				var _this = this;
				uni.getLocation({
					type: 'wgs84',
					success(res) {
						console.log("你当前经纬度是：");
						console.log(res)
						let latitude, longitude;
						latitude = res.latitude.toString();
						longitude = res.longitude.toString();
						_this.myLat = latitude
						_this.myLon = longitude
						//自动获取最近的门店
						_this.request.get("api/stores", {
							"@filter": `math.locationDistance(entity.getLongitude(), entity.getLatitude(), ${longitude}, ${latitude}) < 10 && entity.getStatus() != 1 && entity.getIsDisplay() == true`,
							"@sort": `math.locationDistance(x.getLongitude(),x.getLatitude(),${longitude},${latitude}) > math.locationDistance(y.getLongitude(), y.getLatitude(),${longitude},${latitude})`
						}).then((res) => {
							console.log('stores', res);
							if (res.data.length == 0) {
								_this.getDefaultStore()
							} else {
								let now = new Date()
								let year = now.getFullYear()
								let month = now.getMonth()
								let day = now.getDate()
								let hadInBusiness = false
								for (let i in res.data) {
									let distance = _this.getDistance(res.data[i].latitude, res.data[i]
										.longitude)
									res.data[i]['distance'] = distance
									//判断门店是否在营业时间
									let periods = res.data[i].period.split('-')
									let startTime = periods[0].split(':')
									let endTime = periods[1].split(':')
									if (new Date(year, month, day, startTime[0], startTime[1]).getTime() <
										now.getTime() && now.getTime() < new Date(year, month, day,
											endTime[0], endTime[1]).getTime()) {
										res.data[i]['inBusiness'] = true
										hadInBusiness = true
									} else {
										res.data[i]['inBusiness'] = false
									}
								}
								//如果没有在营业门店，进行提示
								if (!hadInBusiness) {
									uni.showModal({
										title: '温馨提示',
										content: '暂时未有营业门店，您可以先浏览下产品，稍后再下单！',
										showCancel: false,
										success: () => {
											// uni.switchTab({
											// 	url: '/pages/category/category'
											// })
										}
									})
								}
								_this.stores = res.data
								if(res.data[0].region2){
									_this.city = res.data[0].region2.__toString
									_this.regionId = res.data[0].region2.id
								}
							}
						})
					},
					fail() {
						_this.noGps = true
						uni.showModal({
							title: '',
							content: '定位失败，请打开您手机的GPS',
							cancelText: '手动选择',
							confirmColor: '确定',
							success: ((data) => {
								if (data.cancel) {
									_this.getDefaultStore()
								}
							})
						})
					}
				});
			},
			toChooseCity(){
				console.log('fuckU')
				this.showRegions = true
			},
			chooseCity(e){
				console.log(e)
				this.city = e[0].label
				this.regionId = e[0].value
				this.findStore()
			},
			findStore(){
				let filter = `entity.getStatus() != 1 && entity.getIsDisplay() == true`
				if(this.regionId > 0){
					filter += ` && entity.getRegion2().getId() == ${this.regionId}`
				}
				if(this.keyword != ''){
					filter += ` && entity.getName() matches '${this.keyword}'`
				}
				this.request.get(`api/stores`,{
					'@filter': filter
				}).then((res) => {
					console.log('stores',res.data)
					if (res.data.length == 0) {
						this.stores = []
						return
					}
					let now = new Date()
					let year = now.getFullYear()
					let month = now.getMonth()
					let day = now.getDate()
					let hadInBusiness = false
					for (let i in res.data) {
						//判断门店是否在营业时间
						let periods = res.data[i].period.split('-')
						let startTime = periods[0].split(':')
						let endTime = periods[1].split(':')
						if (new Date(year, month, day, startTime[0], startTime[1]).getTime() < now.getTime() && now
							.getTime() < new Date(year, month, day, endTime[0], endTime[1]).getTime()) {
							res.data[i]['inBusiness'] = true
							hadInBusiness = true
						} else {
							res.data[i]['inBusiness'] = false
						}
					}
					//如果没有在营业门店，进行提示
					if (!hadInBusiness) {
						uni.showModal({
							title: '温馨提示',
							content: '暂时未有营业门店，您可以先浏览下产品，稍后再下单！',
							showCancel: false,
							success: () => {
								// uni.switchTab({
								// 	url: '/pages/index/index'
								// })
							}
						})
					}
					this.stores = res.data
					if(res.data && res.data.length > 0 && res.data[0].region2){
						this.city = res.data[0].region2.__toString
						this.regionId = res.data[0].region2.id
					}
				})
			},
			//获取默认的店铺，只有在定位失败的时候运行
			getDefaultStore() {
				this.request.get("api/stores",{'@filter': `entity.getStstus() == 1`}).then((res) => {
					if (res.data.length == 0) {
						uni.showToast({
							title: '所有门店都休息了！',
							icon: 'none'
						})
					}
					let now = new Date()
					let year = now.getFullYear()
					let month = now.getMonth()
					let day = now.getDate()
					let hadInBusiness = false
					for (let i in res.data) {
						//判断门店是否在营业时间
						let periods = res.data[i].period.split('-')
						let startTime = periods[0].split(':')
						let endTime = periods[1].split(':')
						if (new Date(year, month, day, startTime[0], startTime[1]).getTime() < now.getTime() && now
							.getTime() < new Date(year, month, day, endTime[0], endTime[1]).getTime()) {
							res.data[i]['inBusiness'] = true
							hadInBusiness = true
						} else {
							res.data[i]['inBusiness'] = false
						}
					}
					//如果没有在营业门店，进行提示
					this.stores = res.data
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.title {
		color: #606266;
		padding: 10px;
	}

	.name {
		font-weight: bold;
		padding-left: 10px;
		margin-bottom: 5px;
	}

	.more {
		color: #909399;
		font-size: 12px;
		text-align: right;
		padding: 20px 10px;
	}

	.sub-title {
		font-size: 12px;
		color: #909399;
		padding-left: 5px;
		margin-bottom:10px;
	}

	.list {
		margin: 5px;
		background-color: #fff;
		border-radius: 5px;
	}

	.container {
		background-color: #f3f3f3;
		padding: 10px;
		min-height: 100vh;
		overflow: auto;
	}

	.tips {
		color: #F6B423
	}
</style>